package com.gf.forcesystem.websocket;

import com.gf.forcesystem.model.dto.BaseMessage;
import com.gf.forcesystem.model.dto.BaseUnit;
import com.gf.forcesystem.model.dto.IMessage;
import com.gf.forcesystem.scene.SceneManager;
import com.gf.framework.common.exception.BizException;
import com.gf.framework.common.json.GfJsonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author gaofei
 * @date 2022/6/20 21:43
 */
@Component
public class ForceClientWebsocketManager {
    @Autowired
    private SceneManager sceneManager;

    private final Map<String, ForceClientWebSocketServiceImpl> forceWebSocketServiceMap = new ConcurrentHashMap<>();

    /**
     * 注册
     */
    public void register(String userId, ForceClientWebSocketServiceImpl service) throws Exception {
        doRegister(userId, service);
        initSence(service);
    }

    public synchronized void doRegister(String userId, ForceClientWebSocketServiceImpl service) throws Exception{
        if (forceWebSocketServiceMap.containsKey(userId)) {
            throw new BizException("注册失败,已存在用户");
        }
        forceWebSocketServiceMap.put(userId, service);
    }

    /**
     * 首次链接，初始化场景信息
     * @param service
     */
    public void initSence(ForceClientWebSocketServiceImpl service) {
        Map<String, BaseUnit> baseUnitMap = sceneManager.getSceneInfo().getUnitMap();
        for (BaseUnit baseUnit : baseUnitMap.values()) {
            service.sendMessage(baseUnit.toJson());
        }
    }

    public synchronized void unRegister(String userId) {
        forceWebSocketServiceMap.remove(userId);
    }

    /**
     * 获取在线的客户端数量
     * @return
     */
    public int getOnlineNumber() {
        return forceWebSocketServiceMap.size();
    }

    /**
     * 广播消息
     * @param iMessage
     */
    public synchronized void broadcastMessage(IMessage iMessage) {
        broadcastMessage(new BaseMessage(iMessage.getMessageType(), iMessage.getMessageInfo()));
    }

    public synchronized void broadcastMessage(BaseMessage baseMessage) {
        String message = GfJsonMapper.obj2String(baseMessage);
        forceWebSocketServiceMap.values().parallelStream().forEach(service -> service.sendMessage(message));
    }

    public List<String> getOnlineClientIdList() {
        return new ArrayList<>(forceWebSocketServiceMap.keySet());
    }
}
